﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;

namespace ConceptCorporateAdmin
{
    public partial class MidTree : UserControl
    {
        public MidTree()
        {
            InitializeComponent();
        }

        public void generateTreeFromString(String text)
        {
            
            //sterge nodurile precedente
            LstEntitati.Nodes.Clear();
            TreeNode oldNod = null;

            while( text.IndexOf("]") != -1 )
            {
                
                int x = text.IndexOf("[");
                if (text[x + 1].Equals('*'))
                {
                    //facem substring in restul textului
                    text  = text.Substring(x + 1); 
                    int y = text.IndexOf("]");
                    //
                    string sub_part = text.Substring(0, y);
                    //aflam numarul de stelutze
                    int nrStelute   = getNrOfChars('*', sub_part);
                    text  = text.Substring(y + 1);
                    
                    String titlu = text.Substring(0,text.IndexOf("</P>"));

                    if (nrStelute == 1)
                    {
                        //adaugam nod de nivelul 0 , daca [*]
                        oldNod        = LstEntitati.Nodes.Add(titlu); 
                    }
                    else
                    {
                        int new_level = nrStelute - 1;
                        if (new_level < oldNod.Level)
                        {
                            TreeNode new_parent = oldNod.Parent;
                            for (int i = 0; i < oldNod.Level - new_level; i++)
                                new_parent = new_parent.Parent;
                            oldNod = new_parent.Nodes.Add(titlu);
                        }
                        else if (new_level == oldNod.Level)
                        {
                            oldNod = oldNod.Parent.Nodes.Add(titlu);
                        }
                        else
                        {
                            oldNod = oldNod.Nodes.Add(titlu);
                        }
                    }
                }
            }
        }

        private int getNrOfChars(char ch, string text)
        {
            int ret = 0;
            foreach (char c in text.ToCharArray())
            {
                if (c.Equals(ch))
                    ret++;
            }

            return ret;
        }
    }
}
